// 主应用脚本 - 场景管理和UI交互

import * as THREE from 'three';
import { setupScene, GroundScene, createSceneTreeManager, createSceneTreeUI } from '../scene/sceneIndex.js';
import configManager from './config.js';
import projectManager from '../project/projectManager.js';
import projectAPI from '../project/projectAPI.js';
import { initializeModelLibrary } from '../model-library/modelLibraryManager.js';
import { getTransformPanel } from '../scene/TransformPanel.js';
import rightToolbarManager from './rightToolbarManager.js';
import sceneLoader from '../scene/SceneLoader.js';
import { ModelLoader } from '../scene/modelLoader.js';
import { getMaterialEditor } from '../model-library/MaterialEditor.js';
import resourcePreloader from './ResourcePreloader.js';
import EnvironmentManager from '../scene/EnvironmentManager.js';
import ZFightingHelper from '../utils/zFightingHelper.js';
import autoZFightingFixer from '../utils/autoZFightingFixer.js';
import ultimateFixer from '../utils/zFightingUltimateFixer.js';
import '../utils/alphaTransparencyTester.js';
import '../utils/globalTransparencyFixer.js';
import '../utils/transparencyCalculationExplainer.js';
import '../utils/forceTransparencyFix.js';
import skyboxSystem from '../scene/skyboxInit.js';

// 确保 getMaterialEditor 在全局可用
if (!window.getMaterialEditor) {
    window.getMaterialEditor = getMaterialEditor;
}

// 暴露 Z-Fighting 工具到全局
window.ZFightingHelper = ZFightingHelper;
// autoZFightingFixer 会自动暴露到全局，见其模块定义

// 全局自定义确认对话框函数
window.showConfirmDialog = function({ title, message, icon = '', confirmText = '确定', cancelText = '取消', confirmClass = 'modal-btn-primary' }) {
    return new Promise((resolve) => {
        const modal = document.createElement('div');
        modal.className = 'custom-modal';
        
        const content = document.createElement('div');
        content.className = 'modal-content';
        
        // 标题
        const header = document.createElement('div');
        header.className = 'modal-header';
        if (icon) {
            const iconEl = document.createElement('span');
            iconEl.className = 'modal-header-icon';
            iconEl.textContent = icon;
            header.appendChild(iconEl);
        }
        const titleEl = document.createElement('span');
        titleEl.textContent = title;
        header.appendChild(titleEl);
        
        // 内容
        const body = document.createElement('div');
        body.className = 'modal-body';
        const messageEl = document.createElement('div');
        messageEl.className = 'modal-message';
        messageEl.style.whiteSpace = 'pre-wrap'; // 支持换行
        messageEl.textContent = message;
        body.appendChild(messageEl);
        
        // 底部按钮
        const footer = document.createElement('div');
        footer.className = 'modal-footer';
        
        // 如果有取消按钮文字，则显示取消按钮
        if (cancelText) {
            const cancelBtn = document.createElement('button');
            cancelBtn.className = 'modal-btn modal-btn-secondary';
            cancelBtn.textContent = cancelText;
            cancelBtn.onclick = () => {
                document.body.removeChild(modal);
                resolve(false);
            };
            footer.appendChild(cancelBtn);
        }
        
        const confirmBtn = document.createElement('button');
        confirmBtn.className = `modal-btn ${confirmClass}`;
        confirmBtn.textContent = confirmText;
        confirmBtn.onclick = () => {
            document.body.removeChild(modal);
            resolve(true);
        };
        
        footer.appendChild(confirmBtn);
        
        content.appendChild(header);
        content.appendChild(body);
        content.appendChild(footer);
        modal.appendChild(content);
        
        // 点击背景关闭
        modal.onclick = (e) => {
            if (e.target === modal) {
                document.body.removeChild(modal);
                resolve(false);
            }
        };
        
        // ESC 键关闭
        const escHandler = (e) => {
            if (e.key === 'Escape') {
                document.body.removeChild(modal);
                resolve(false);
                document.removeEventListener('keydown', escHandler);
            }
        };
        document.addEventListener('keydown', escHandler);
        
        document.body.appendChild(modal);
        confirmBtn.focus();
    });
};

// 全局自定义输入对话框函数
window.showInputDialog = function({ title, message, defaultValue = '' }) {
    return new Promise((resolve) => {
        const modal = document.createElement('div');
        modal.className = 'custom-modal';
        
        const content = document.createElement('div');
        content.className = 'modal-content';
        
        // 标题
        const header = document.createElement('div');
        header.className = 'modal-header';
        const titleEl = document.createElement('span');
        titleEl.textContent = title;
        header.appendChild(titleEl);
        
        // 内容
        const body = document.createElement('div');
        body.className = 'modal-body';
        if (message) {
            const messageEl = document.createElement('div');
            messageEl.className = 'modal-message';
            messageEl.textContent = message;
            body.appendChild(messageEl);
        }
        
        const input = document.createElement('input');
        input.type = 'text';
        input.className = 'modal-input';
        input.value = defaultValue;
        body.appendChild(input);
        
        // 底部按钮
        const footer = document.createElement('div');
        footer.className = 'modal-footer';
        
        const cancelBtn = document.createElement('button');
        cancelBtn.className = 'modal-btn modal-btn-secondary';
        cancelBtn.textContent = '取消';
        cancelBtn.onclick = () => {
            document.body.removeChild(modal);
            resolve(null);
        };
        
        const confirmBtn = document.createElement('button');
        confirmBtn.className = 'modal-btn modal-btn-primary';
        confirmBtn.textContent = '确定';
        const confirmHandler = () => {
            const value = input.value;
            document.body.removeChild(modal);
            resolve(value);
        };
        confirmBtn.onclick = confirmHandler;
        
        footer.appendChild(cancelBtn);
        footer.appendChild(confirmBtn);
        
        content.appendChild(header);
        content.appendChild(body);
        content.appendChild(footer);
        modal.appendChild(content);
        
        // 点击背景关闭
        modal.onclick = (e) => {
            if (e.target === modal) {
                document.body.removeChild(modal);
                resolve(null);
            }
        };
        
        // Enter键确认，ESC键取消
        const keyHandler = (e) => {
            if (e.key === 'Enter') {
                confirmHandler();
                document.removeEventListener('keydown', keyHandler);
            } else if (e.key === 'Escape') {
                document.body.removeChild(modal);
                resolve(null);
                document.removeEventListener('keydown', keyHandler);
            }
        };
        document.addEventListener('keydown', keyHandler);
        
        document.body.appendChild(modal);
        input.focus();
        input.select();
    });
};

try {
    // 步骤 1: 等待配置加载
    await configManager.loadConfig();
    configManager.applyConfig();
    // 步骤 2-5: 完整的加载流程（项目+场景）
    let currentProject = null;
    let scenes = [];
    let manager = null;
    let defaultSceneId = null;
    let sceneTreeManager = null;
    let sceneTreeUI = null;
    
    // 暴露 projectManager 到全局（供 ModelLoader 使用）
    window.projectManager = projectManager;
    
    // 创建模型加载器实例（必须在场景加载前初始化）
    const modelLoader = new ModelLoader();
    window.modelLoader = modelLoader;
    // 使用项目加载界面完成所有初始化（双阶段同时显示）
    // isInitial=true 表示这是页面加载时的初始化，界面已经在HTML中显示了
    await sceneLoader.performProjectLoading(async (loader) => {
        // === 阶段1: 加载项目 (0-100%) ===
        loader.updateStage('project', 0, '正在初始化...');
        
        // 初始化项目
        loader.updateStage('project', 10, '正在读取项目配置...');
        currentProject = await projectManager.initialize();
        
        if (!currentProject) {
            throw new Error('项目初始化失败 - 未找到可用项目');
        }
        
        // 设置全局项目ID，供其他模块使用（如贴图库）
        window.currentProjectId = currentProject.id;
        
        loader.updateStage('project', 30, `加载项目: ${currentProject.name}`);
        
                // 🎨 初始化材质库
                loader.updateStage('project', 40, '正在加载材质库...');
                if (window.getMaterialLibraryManager) {
                    try {
                        const materialLibraryManager = window.getMaterialLibraryManager(currentProject.id);
                        await materialLibraryManager.loadMaterials();
                        // 暴露到全局，方便其他模块使用
                        window.materialLibraryManager = materialLibraryManager;
                    } catch (error) {
                        console.error('❌ 材质库加载失败:', error);
                    }
                }
                
                // 📦 预加载所有资源（材质和纹理）
                loader.updateStage('project', 50, '正在预加载资源...');
                try {
                    await resourcePreloader.preloadProjectResources(
                        currentProject.id,
                        (loaded, total) => {
                            // 更新进度：50-65%
                            const progress = 50 + Math.round((loaded / total) * 15);
                            loader.updateStage('project', progress, `预加载资源: ${loaded}/${total}`);
                        }
                    );
                    // 暴露到全局，供其他模块使用
                    window.resourcePreloader = resourcePreloader;
                } catch (error) {
                    console.error('❌ 资源预加载失败:', error);
                }
                
                // 获取场景列表
                loader.updateStage('project', 65, '正在获取场景列表...');
                scenes = projectManager.getScenes();
                
                if (!scenes || scenes.length === 0) {
                    console.warn('⚠️ 当前项目没有场景配置');
                }
        
        // 初始化场景管理器
        loader.updateStage('project', 75, '正在初始化3D引擎...');
        manager = setupScene(document.body);
        
        // 暴露 manager 到全局（供 SceneTreeUI、TransformPanel 等使用）
        window.manager = manager;
        // 注册场景
        loader.updateStage('project', 90, '正在注册场景...');
        const sceneTypeMap = {
            'GroundScene': GroundScene
        };
        
        let registeredCount = 0;
        scenes.forEach(sceneConfig => {
            const SceneClass = sceneTypeMap[sceneConfig.type];
            if (SceneClass) {
                manager.registerScene(sceneConfig.id, SceneClass);
                registeredCount++;
            } else {
                console.warn(`   ⚠️ 未找到场景类型: ${sceneConfig.type}`);
            }
        });
        loader.updateStage('project', 100, '项目加载完成');
        
        // === 阶段2: 加载默认场景 (0-100%) ===
        loader.updateStage('scene', 0, '正在准备场景...');
        
        defaultSceneId = projectManager.getDefaultSceneId();
        const sceneIdToLoad = defaultSceneId || (scenes.length > 0 ? scenes[0].id : null);
        
        if (sceneIdToLoad) {
            loader.updateStage('scene', 5, '正在切换场景...');
            const success = manager.switchScene(sceneIdToLoad);
            
            if (success) {
                const currentScene = manager.getCurrentScene();
                if (currentScene && currentScene.scene) {
                    // ===== 步骤1: 优先加载环境模型 (5-20%) =====
                    loader.updateStage('scene', 10, '正在初始化环境...');
                    
                    // 创建环境管理器
                    const environmentManager = new EnvironmentManager(
                        currentScene.scene,
                        currentProject.id,
                        sceneIdToLoad
                    );
                    
                    // 初始化天空盒系统
                    if (currentScene.scene && manager.renderer) {
                        skyboxSystem.init(currentScene.scene, manager.renderer);
                        console.log('✅ 天空盒系统已初始化');
                    }
                    
                    // 初始化环境管理器（加载配置）
                    await environmentManager.initialize();
                    
                    // 加载环境模型（如果有配置）
                    if (environmentManager.config.environmentModel) {
                        await environmentManager.loadEnvironmentModel((progress, detail) => {
                            const p = 10 + Math.round((progress / 100) * 10); // 10-20%
                            loader.updateStage('scene', p, detail);
                        });
                    }
                    
                    // 暴露到全局
                    window.environmentManager = environmentManager;
                    
                    // ===== 步骤2: 初始化场景树并加载场景树数据 (20-80%) =====
                    loader.updateStage('scene', 20, '正在初始化场景树...');
                    
                    // 调用完整的初始化函数（与切换场景相同）
                    initializeSceneTree(currentScene.scene);
                    
                    // 在同一个 loader 中加载场景数据（使用 scene 阶段）
                    await loadSceneTreeData(sceneIdToLoad, loader, 20, 60, 'scene');
                    
                    // ===== 步骤3: 最后应用环境光 (80-95%) =====
                    loader.updateStage('scene', 85, '正在应用环境光...');
                    await environmentManager.applyAmbientLight();
                    
                    // 初始化比例尺按钮状态
                    loader.updateStage('scene', 95, '初始化UI...');
                    const scaleGridBtn = document.getElementById('scaleGridBtn');
                    if (scaleGridBtn && currentScene.scaleGrid) {
                        if (currentScene.scaleGrid.visible) {
                            scaleGridBtn.classList.add('active');
                        } else {
                            scaleGridBtn.classList.remove('active');
                        }
                    }
                    
                    loader.updateStage('scene', 100, '场景加载完成');
                    
                    // 触发场景加载完成事件，用于初始化UI
                    window.dispatchEvent(new Event('sceneLoaded'));
                }
            } else {
                console.error('❌ 场景切换失败');
                loader.updateStage('scene', 100, '场景切换失败');
            }
        } else {
            console.warn('⚠️ 没有可加载的场景');
            loader.updateStage('scene', 100, '无场景可加载');
        }
    }, true); // true = isInitial，表示页面初始加载
    
    // 编辑端固定为编辑模式
    // 检查认证状态，决定是否显示账号相关信息
    const authConfig = configManager.getAuthConfig();
    const authEnabled = authConfig.enabled !== false;
    if (authEnabled) {
        // 启用认证时，显示账号信息和退出登录按钮
        const username = localStorage.getItem('username') || configManager.get('auth.defaultUsername');
        const currentUserElement = document.getElementById('current-user');
        if (currentUserElement) {
            currentUserElement.textContent = username || '未登录';
        }
        
        // 显示所有带 auth-only 类的元素
        document.querySelectorAll('.auth-only').forEach(el => {
            el.style.display = '';
        });
        
        // 绑定退出登录按钮
        const logoutBtn = document.getElementById('logoutBtn');
        if (logoutBtn) {
            logoutBtn.addEventListener('click', function() {
                if (confirm('确定要退出登录吗？')) {
                    // 清除登录状态
                    localStorage.removeItem('isLoggedIn');
                    localStorage.removeItem('username');
                    localStorage.removeItem('loginTime');
                    localStorage.removeItem('sessionTimeout');
                    window.location.href = 'login.html';
                }
            });
        }
    } else {
        // 未启用认证时，隐藏账号信息和退出登录按钮
        document.querySelectorAll('.auth-only').forEach(el => {
            el.style.display = 'none';
        });
    }
    
    // 显示当前项目名称
    const projectNameElement = document.getElementById('current-project-name');
    if (projectNameElement) {
        projectNameElement.textContent = currentProject.name;
    }
    
    // 更新浏览器标签页标题
    document.title = `${currentProject.name} - 组态可视化系统`;
    
    // 绑定设置按钮
    const settingsBtn = document.getElementById('settingsBtn');
    if (settingsBtn) {
        settingsBtn.addEventListener('click', function() {
            openSettingsPanel();
        });
    }
    
    // 设置面板函数
    window.openSettingsPanel = function() {
        const panel = document.getElementById('settings-panel');
        panel.classList.add('active');
    };
    
    window.closeSettingsPanel = function() {
        const panel = document.getElementById('settings-panel');
        panel.classList.remove('active');
    };
    
    window.openAdminPage = function() {
            window.location.href = 'admin.html';
    };
    
    // 点击模态框背景关闭
    document.getElementById('settings-panel').addEventListener('click', function(e) {
        if (e.target === this) {
            closeSettingsPanel();
        }
    });
    
    // 初始化模型库管理器（已从app.js剥离到独立模块）
    initializeModelLibrary(manager);
    
    // 初始化场景树UI
    // 参数 scene 是 THREE.Scene 对象
    function initializeSceneTree(threeScene) {
        const treeContainer = document.getElementById('scene-tree-container');
        if (!treeContainer) {
            console.warn('⚠️ 场景树容器未找到');
            return;
        }
        // 创建场景树管理器（需要 THREE.Scene）
        sceneTreeManager = createSceneTreeManager(threeScene);
        
        // 编辑端固定为编辑模式
        sceneTreeUI = createSceneTreeUI(treeContainer, sceneTreeManager, 'edit');
        
        // 绑定到全局，方便调试
        window.sceneTreeManager = sceneTreeManager;
        window.sceneTreeUI = sceneTreeUI;
        
        // 初始化Transform面板
        const transformPanel = getTransformPanel();
        transformPanel.setTreeManager(sceneTreeManager, sceneTreeUI);
        
        // 暴露为全局变量，供 HTML onclick 使用
        window.transformPanel = transformPanel;
        
        // 初始化右侧工具栏管理器
        rightToolbarManager.setTransformPanel(transformPanel);
        
        // 获取当前场景实例，设置 Transform 控制器
        const currentScene = manager.getCurrentScene();
        if (currentScene) {
            // 初始化 Transform 控制器（如果尚未初始化）
            if (!currentScene.transformControlsManager) {
                currentScene.setupTransformControls(manager.renderer);
            }
            
            const transformControls = currentScene.getTransformControls();
            if (transformControls) {
                // 设置 Transform 变化回调，实时同步更新节点数据
                transformControls.onChange((node, object3D) => {
                    if (!node || !object3D) return;
                    
                    // 1. 更新节点的 transform 数据（注意：是 node.transform 而不是 node 直接属性）
                    // 注意：rotation 存储为弧度值，TransformPanel 会在显示时转换为角度
                    node.transform.position = {
                        x: parseFloat(object3D.position.x.toFixed(3)),
                        y: parseFloat(object3D.position.y.toFixed(3)),
                        z: parseFloat(object3D.position.z.toFixed(3))
                    };
                    node.transform.rotation = {
                        x: parseFloat(object3D.rotation.x.toFixed(4)),  // 存储弧度值
                        y: parseFloat(object3D.rotation.y.toFixed(4)),
                        z: parseFloat(object3D.rotation.z.toFixed(4))
                    };
                    // ✅ scale 需要除以 originalScale（模型原始缩放），而不是 baseScale
                    // originalScale 只用于显示调整，不参与 transform.scale 的语义
                    const originalScale = node.originalScale || { x: 1, y: 1, z: 1 };
                    
                    // 获取父节点的世界缩放
                    let parentWorldScale = new THREE.Vector3(1, 1, 1);
                    if (object3D.parent) {
                        object3D.parent.getWorldScale(parentWorldScale);
                    }
                    
                    // 计算世界缩放，然后除以originalScale得到transform.scale
                    const worldScale = new THREE.Vector3();
                    object3D.getWorldScale(worldScale);
                    
                    node.transform.scale = {
                        x: parseFloat((worldScale.x / originalScale.x).toFixed(3)),
                        y: parseFloat((worldScale.y / originalScale.y).toFixed(3)),
                        z: parseFloat((worldScale.z / originalScale.z).toFixed(3))
                    };
                    
                    // 2. 实时更新 Transform 面板显示（如果面板打开且是当前节点）
                    if (transformPanel && transformPanel.currentNode === node) {
                        transformPanel.show(node);
                    }
                    
                    // 3. 通知场景树管理器节点数据已更新
                    if (sceneTreeManager) {
                        sceneTreeManager.updateNode(node.id, node);
                    }

                    // 4. 🎥 如果是相机节点，实时更新相机面板
                    if (node.type === 'camera' && window.rightToolbarManager && window.rightToolbarManager.cameraPanel) {
                        window.rightToolbarManager.cameraPanel.updateUI();
                    }
                });
                
                    // 设置鼠标释放回调，保存数据
                    transformControls.onMouseUp((node, object3D) => {
                        if (!node || !object3D) return;
                        
                        // 📝 记录编辑过的节点（用于批量重置）
                        if (object3D.isMesh && window.sceneTreeUI && window.sceneTreeUI._editedNodes) {
                            let meshNode = null;
                            
                            // 方法1: 通过mesh-node缓存查找节点
                            if (window.sceneTreeUI.meshNodeCache && window.sceneTreeUI.meshNodeCache.has(object3D.uuid)) {
                                meshNode = window.sceneTreeUI.meshNodeCache.get(object3D.uuid);
                            } 
                            // 方法2: 如果缓存中没有，遍历场景树查找（更可靠）
                            else if (window.sceneTreeManager) {
                                // 遍历所有节点，找到包含此mesh的节点
                                window.sceneTreeManager.traverse(node => {
                                    if (node.object3D && node.modelId) {
                                        // 检查这个mesh是否是该节点的子对象
                                        let found = false;
                                        node.object3D.traverse(child => {
                                            if (child.uuid === object3D.uuid) {
                                                found = true;
                                            }
                                        });
                                        if (found) {
                                            meshNode = node;
                                            // 同时更新缓存，避免重复查找
                                            window.sceneTreeUI.meshNodeCache.set(object3D.uuid, node);
                                        }
                                    }
                                });
                            }
                            // 方法3: 使用当前编辑节点作为后备
                            if (!meshNode) {
                                meshNode = window.sceneTreeUI._currentMeshEditNode;
                            }
                            
                            if (meshNode) {
                                window.sceneTreeUI._editedNodes.add(meshNode);
                            } else {
                                console.warn(`⚠️ 无法找到mesh所属的节点: "${object3D.name}"`);
                            }
                        }
                        
                        // 触发场景树变化事件，自动保存到服务器
                        window.dispatchEvent(new Event('sceneTreeChanged'));
                    });
            }
        }
        
        // 监听节点选中事件
        sceneTreeManager.on('nodeSelected', ({ node, previousNode }) => {
            // 🎥 相机Helper处理：隐藏上一个相机的Helper
            if (previousNode && previousNode.type === 'camera' && previousNode.object3D && previousNode.object3D.userData.helper) {
                previousNode.object3D.userData.helper.visible = false;
            }
            
            // 🎥 相机Helper处理：显示当前相机的Helper
            if (node.type === 'camera' && node.object3D && node.object3D.userData.helper) {
                node.object3D.userData.helper.visible = true;
            }
            
            // 更新Transform面板内容
            // transformPanel.show(node); // 不要自动显示，让用户通过Tab打开
            // 只通知右侧工具栏管理器
            rightToolbarManager.onNodeSelected(node);
            
            // 附加 Transform 控制器到选中的节点
            const currentScene = manager.getCurrentScene();
            if (!currentScene) {
                console.error('❌ [场景树事件] 无法获取当前场景');
                return;
            }
            
            // 如果 Transform 控制器未初始化，立即初始化
            if (!currentScene.transformControlsManager) {
                console.warn('⚠️ [场景树事件] Transform 控制器未初始化，立即初始化...');
                currentScene.setupTransformControls(manager.renderer);
                
                // 重新设置回调（因为是新初始化的）
                const transformControls = currentScene.getTransformControls();
                if (transformControls) {
                    transformControls.onChange((node, object3D) => {
                        if (!node || !object3D) return;
                        
                        // ✅ 获取世界坐标（TransformControls 操作的是世界坐标）
                        const worldPos = new THREE.Vector3();
                        const worldQuat = new THREE.Quaternion();
                        const worldScale = new THREE.Vector3();
                        
                        object3D.getWorldPosition(worldPos);
                        object3D.getWorldQuaternion(worldQuat);
                        object3D.getWorldScale(worldScale);
                        
                        // 将四元数转换为欧拉角
                        const worldEuler = new THREE.Euler().setFromQuaternion(worldQuat);
                        
                        // 保存世界坐标到 node.transform
                        node.transform.position = {
                            x: parseFloat(worldPos.x.toFixed(3)),
                            y: parseFloat(worldPos.y.toFixed(3)),
                            z: parseFloat(worldPos.z.toFixed(3))
                        };
                        node.transform.rotation = {
                            x: parseFloat(worldEuler.x.toFixed(4)),
                            y: parseFloat(worldEuler.y.toFixed(4)),
                            z: parseFloat(worldEuler.z.toFixed(4))
                        };
                        node.transform.scale = {
                            x: parseFloat(worldScale.x.toFixed(3)),
                            y: parseFloat(worldScale.y.toFixed(3)),
                            z: parseFloat(worldScale.z.toFixed(3))
                        };
                        
                        // 实时更新 Transform 面板
                        if (transformPanel && transformPanel.currentNode === node) {
                            transformPanel.show(node);
                        }
                        
                        // 通知场景树管理器
                        if (sceneTreeManager) {
                            sceneTreeManager.updateNode(node.id, node);
                        }
                    });
                    
                    transformControls.onMouseUp((node, object3D) => {
                        if (!node || !object3D) return;
                        
                        // 📝 记录编辑过的节点（用于批量重置）
                        if (object3D.isMesh && window.sceneTreeUI && window.sceneTreeUI._editedNodes) {
                            let meshNode = null;
                            
                            // 方法1: 通过mesh-node缓存查找节点
                            if (window.sceneTreeUI.meshNodeCache && window.sceneTreeUI.meshNodeCache.has(object3D.uuid)) {
                                meshNode = window.sceneTreeUI.meshNodeCache.get(object3D.uuid);
                            } 
                            // 方法2: 如果缓存中没有，遍历场景树查找（更可靠）
                            else if (window.sceneTreeManager) {
                                window.sceneTreeManager.traverse(n => {
                                    if (n.object3D && n.modelId) {
                                        let found = false;
                                        n.object3D.traverse(child => {
                                            if (child.uuid === object3D.uuid) {
                                                found = true;
                                            }
                                        });
                                        if (found) {
                                            meshNode = n;
                                            window.sceneTreeUI.meshNodeCache.set(object3D.uuid, n);
                                        }
                                    }
                                });
                            }
                            // 方法3: 使用当前编辑节点作为后备
                            if (!meshNode) {
                                meshNode = window.sceneTreeUI._currentMeshEditNode;
                            }
                            
                            if (meshNode) {
                                window.sceneTreeUI._editedNodes.add(meshNode);
                            }
                        }
                        
                        window.dispatchEvent(new Event('sceneTreeChanged'));
                    });
                }
            }
            
            // 从当前场景的 THREE.Scene 中查找对象
            // ✅ node.id 就是 object3D.uuid
            const object3D = threeScene.getObjectByProperty('uuid', node.id);
            
            if (object3D) {
                currentScene.transformControlsManager.attach(object3D, node);
            } else {
                console.warn(`⚠️ [场景树事件] 未找到节点对应的3D对象: ${node.name} (id: ${node.id})`);
                const objByName = threeScene.getObjectByName(node.name);
                if (objByName) {
                    currentScene.transformControlsManager.attach(objByName, node);
                } else {
                    console.error('❌ [场景树事件] 无法找到对象');
                }
            }
        });
        
        // 监听节点取消选中事件
        sceneTreeManager.on('nodeDeselected', async ({ previousNode }) => {
            // 🎥 相机Helper处理：隐藏被取消选中的相机的Helper
            if (previousNode && previousNode.type === 'camera' && previousNode.object3D && previousNode.object3D.userData.helper) {
                previousNode.object3D.userData.helper.visible = false;
            }
            
            // transformPanel.hide(); // 不要自动隐藏
            await rightToolbarManager.onNodeDeselected();
            
            // 注意：不需要在这里手动detach TransformControls
            // SceneTreeUI.clearSelection() 已经统一处理了所有清理逻辑
        });
        
        // 监听节点删除事件
        sceneTreeManager.on('nodeRemoved', ({ node }) => {
            // 🎥 清理相机 Helper
            if (node.type === 'camera' && node.object3D && node.object3D.userData.helper) {
                const helper = node.object3D.userData.helper;
                if (helper.parent) {
                    helper.parent.remove(helper);
                }
                // 释放资源
                if (helper.geometry) helper.geometry.dispose();
                if (helper.material) helper.material.dispose();
                node.object3D.userData.helper = null;
            }

            // 注意：removeNode() 方法已经在删除前自动取消选中并分离控制器
            // 这里保留为双重保险，防止某些边缘情况
            const currentScene = manager.getCurrentScene();
            if (currentScene && currentScene.transformControlsManager) {
                const tcm = currentScene.transformControlsManager;
                
                // 如果控制器仍然附加着被删除的节点，强制分离
                if (tcm.currentNode && tcm.currentNode.id === node.id) {
                    console.warn('⚠️ [场景树事件] 控制器未正确分离，强制分离...');
                    tcm.detach();
                }
            }
        });
        
        // 监听节点移动事件（重新父化）
        sceneTreeManager.on('nodeMoved', ({ node, oldParent, newParent }) => {
            // 如果移动的节点是当前选中的节点，需要重新附加 Transform Controls
            // 因为父子关系改变后，object3D 的坐标系也改变了
            if (sceneTreeManager.selectedNode && sceneTreeManager.selectedNode.id === node.id) {
                const currentScene = manager.getCurrentScene();
                if (currentScene && currentScene.transformControlsManager) {
                    // 重新附加到同一个 object3D（世界坐标已经通过 attach() 保持不变）
                    currentScene.transformControlsManager.attach(node.object3D, node);
                    // 更新 Transform 面板显示（显示新的本地坐标）
                    if (transformPanel && transformPanel.currentNode === node) {
                        transformPanel.show(node);
                    }
                }
            }
        });
    }
    
    // 监听场景树变化事件，自动保存
    window.addEventListener('sceneTreeChanged', () => {
        const currentSceneId = manager.getCurrentSceneName();
        if (currentSceneId) {
            saveSceneTreeData(currentSceneId);
        }
    });
    
    // 从服务器加载场景树数据
    // 参数 existingLoader: 如果提供，则在现有 loader 中更新进度，否则创建新的加载界面
    // 参数 progressOffset: 进度偏移量（用于连续加载）
    // 参数 progressRange: 进度范围（用于连续加载）
    async function loadSceneTreeData(sceneId, existingLoader = null, progressOffset = 0, progressRange = 100, stageName = null) {
        try {
            const projectId = projectManager.getCurrentProject().id;
            
            // 内部加载函数
            const loadTreeData = async (loader) => {
                // 决定使用 updateStage 还是 updateProgress（兼容旧版本）
                const updateProgress = (percent, detail) => {
                    if (stageName && loader.updateStage) {
                        // 新版本：使用阶段更新
                        loader.updateStage(stageName, percent, detail);
                    } else if (loader.updateProgress) {
                        // 旧版本：使用进度更新
                        const calcProgress = (p) => progressOffset + Math.round((p / 100) * progressRange);
                        loader.updateProgress(calcProgress(percent), detail);
                    }
                };
                
                // 更新进度: 获取数据
                updateProgress(10, '正在获取场景数据...');
                
                const response = await fetch(`/api/projects/${projectId}/scenes/${sceneId}/tree`);
                
                if (!response.ok) {
                    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
                }
                
                const treeData = await response.json();
                
                if (treeData && sceneTreeUI) {
                    // 计算节点总数（简单估算）
                    const countNodes = (node) => {
                        let count = 1;
                        if (node.children) {
                            node.children.forEach(child => count += countNodes(child));
                        }
                        return count;
                    };
                    
                    const totalNodes = treeData.root && treeData.root.children
                        ? treeData.root.children.reduce((sum, child) => sum + countNodes(child), 0)
                        : 0;
                    
                    loader.setTotalItems(totalNodes);
                    
                    // 🎯 加载场景树，传递进度回调（支持四阶段进度）
                    await sceneTreeUI.loadFromJSON(treeData, (current, total, nodeName, nodeType) => {
                        let progress, message;
                        
                        // 区分四个阶段的进度
                        if (nodeType === 'parse-step') {
                            // 🎯 第零阶段：解析场景数据（10%~20%）
                            progress = 10 + Math.round((current / total) * 10);
                            message = nodeName;
                        } else if (nodeType === 'model-download') {
                            // 🎯 第一阶段-实时：模型下载进度（20%~60%，支持小数进度）
                            progress = 20 + ((current / total) * 40);
                            message = nodeName; // nodeName 已包含下载进度信息
                        } else if (nodeType === 'model-preload') {
                            // 🎯 第一阶段-完成：模型预加载完成（20%~60%）
                            progress = 20 + Math.round((current / total) * 40);
                            message = nodeName;
                        } else {
                            // 🎯 第二阶段：构建场景树（60%~90%）
                            progress = 60 + Math.round((current / total) * 30);
                            message = `加载节点: ${nodeName}`;
                        }
                        
                        updateProgress(progress, message);
                        
                        // 添加/更新加载项
                        if (nodeType === 'model-preload') {
                            // 显示模型加载完成项
                            const itemId = `model-${current}`;
                            if (!loader.loadingItems.has(itemId)) {
                                // 使用 'model' 类型图标
                                loader.addLoadingItem(itemId, nodeName, 'model');
                            }
                            loader.updateLoadingItem(itemId, 'completed');
                        } else if (nodeType !== 'parse-step' && nodeType !== 'model-download') {
                            // 显示节点加载完成项（第二阶段）
                            const itemId = `node-${current}`;
                            if (!loader.loadingItems.has(itemId)) {
                                loader.addLoadingItem(itemId, nodeName, nodeType);
                            }
                            loader.updateLoadingItem(itemId, 'completed');
                        }
                    });
                    // 更新进度: 初始化控制器
                    updateProgress(95, '初始化场景控制器...');
                    
                    // 确保 Transform Controls 已初始化
                    const currentScene = manager.getCurrentScene();
                    if (currentScene && !currentScene.transformControlsManager) {
                        currentScene.setupTransformControls(manager.renderer);
                    }
                    
                    // 完成
                    updateProgress(100, '加载完成！');
                }
            };
            
            // 如果提供了现有 loader，直接在其中加载
            if (existingLoader) {
                await loadTreeData(existingLoader);
            } else {
                // 否则创建新的场景加载界面
                const success = await sceneLoader.performSceneLoading(loadTreeData);
                
                if (!success) {
                    // 加载失败，显示空场景树
                    if (sceneTreeUI) {
                        sceneTreeUI.render();
                    }
                }
            }
            
        } catch (error) {
            console.error('❌ 加载场景树数据异常:', error.message);
            if (sceneTreeUI) {
                sceneTreeUI.render();
            }
        }
    }
    
    // 保存场景树数据到服务器
    async function saveSceneTreeData(sceneId) {
        if (!sceneTreeUI) return;
        
        try {
            const projectId = projectManager.getCurrentProject().id;
            const treeData = sceneTreeUI.toJSON();
            
            const response = await fetch(
                `/api/projects/${projectId}/scenes/${sceneId}/tree`,
                {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(treeData)
                }
            );
            
            if (!response.ok) {
                console.error('❌ 保存场景树数据失败');
            }
        } catch (error) {
            console.error('❌ 保存场景树数据失败:', error);
        }
    }
    
    // 全局函数：添加空节点
    window.addEmptyNode = function() {
        if (!sceneTreeUI || !sceneTreeManager) {
            console.warn('⚠️ 场景树未初始化');
            return;
        }
        
        // 直接命名为"空节点"，不弹窗
        const nodeName = '空节点';
        
        // 创建空的 Three.js Group 对象
        const emptyGroup = new THREE.Group();
        emptyGroup.name = nodeName;
        
        // 添加到当前场景
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.scene) {
            currentScene.scene.add(emptyGroup);
            
            // 添加到场景树
            const newNode = sceneTreeManager.addNode({
                name: nodeName,
                type: 'group',
                object3D: emptyGroup,
                visible: true,
                locked: false
            });
            
            if (newNode) {
                sceneTreeUI.refresh();
                // 触发场景树变化事件，自动同步后端
                sceneTreeUI.notifyTreeChanged();
            } else {
                console.error('❌ 添加空节点失败');
                currentScene.scene.remove(emptyGroup);
            }
        } else {
            console.error('❌ 当前场景不存在');
        }
    };

    // 全局函数：点击标题栏相机按钮（选择相机或创建相机）
    window.onCameraTitleButtonClick = function() {
        if (!sceneTreeUI || !sceneTreeManager) {
            console.warn('⚠️ 场景树未初始化');
            return;
        }
        
        // 1. 查找现有相机
        let cameraNode = null;
        sceneTreeManager.traverse(node => {
            if (node.type === 'camera' && !cameraNode) {
                cameraNode = node;
            }
        });
        
        if (cameraNode) {
            // 2. 如果存在相机，选中它
            sceneTreeManager.selectNode(cameraNode.id);
            window.showMessage('已选中场景中的相机', 'success');
        } else {
            // 3. 如果不存在，创建新相机
            window.addCameraNode();
        }
    };

    // 全局函数：添加相机节点
    window.addCameraNode = function() {
        if (!sceneTreeUI || !sceneTreeManager) {
            console.warn('⚠️ 场景树未初始化');
            return;
        }
        
        const nodeName = 'Camera';
        
        // 创建相机
        const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.name = nodeName;
        
        // 添加到当前场景
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.scene) {
            // 创建 Helper
            const helper = new THREE.CameraHelper(camera);
            helper.name = nodeName + '_Helper';
            camera.userData.helper = helper;
            currentScene.scene.add(helper); // Helper 必须添加到场景才能显示
            helper.visible = true; // 选中时显示，这里默认选中
            
            // 🎥 添加相机简模（可视化Mesh）
            const cameraGroup = new THREE.Group();
            cameraGroup.name = 'CameraModel';
            const bodyGeometry = new THREE.BoxGeometry(0.4, 0.3, 0.2);
            const bodyMaterial = new THREE.MeshBasicMaterial({ color: 0x333333 });
            const bodyMesh = new THREE.Mesh(bodyGeometry, bodyMaterial);
            const lensGeometry = new THREE.CylinderGeometry(0.1, 0.1, 0.2, 16);
            lensGeometry.rotateX(-Math.PI / 2);
            const lensMaterial = new THREE.MeshBasicMaterial({ color: 0x111111 });
            const lensMesh = new THREE.Mesh(lensGeometry, lensMaterial);
            lensMesh.position.z = -0.15;
            cameraGroup.add(bodyMesh);
            cameraGroup.add(lensMesh);
            camera.add(cameraGroup);
            
            // 添加到场景树
            const newNode = sceneTreeManager.addNode({
                name: nodeName,
                type: 'camera',
                object3D: camera,
                visible: true,
                locked: false,
                components: [
                    {
                        type: 'camera',
                        fov: 50,
                        near: 0.1,
                        far: 1000
                    },
                    {
                         type: 'transform',
                         position: { x: 0, y: 2, z: 5 },
                         rotation: { x: 0, y: 0, z: 0 },
                         scale: { x: 1, y: 1, z: 1 }
                    }
                ]
            });
            
            if (newNode) {
                // 应用默认位置
                camera.position.set(0, 2, 5);
                newNode.updateTransform(newNode.getLocalTransform());
                
                // 选中新创建的相机
                sceneTreeManager.selectNode(newNode.id);
                
                sceneTreeUI.refresh();
                sceneTreeUI.notifyTreeChanged();
            } else {
                console.error('❌ 添加相机节点失败');
                currentScene.scene.remove(helper);
            }
        } else {
            console.error('❌ 当前场景不存在');
        }
    };
    
    // 全局函数：设置 Transform 模式
    window.setTransformMode = function(mode) {
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.transformControlsManager) {
            currentScene.transformControlsManager.setMode(mode);
            
            // 更新按钮状态
            const buttons = {
                'translate': document.getElementById('transformTranslateBtn'),
                'rotate': document.getElementById('transformRotateBtn'),
                'scale': document.getElementById('transformScaleBtn')
            };
            
            // 移除所有按钮的 active 类
            Object.values(buttons).forEach(btn => {
                if (btn) btn.classList.remove('active');
            });
            
            // 添加当前模式按钮的 active 类
            if (buttons[mode]) {
                buttons[mode].classList.add('active');
            }
        }
    };
    
    // 全局调试函数
    window.debugTransformControls = function() {
        const scene = manager?.getCurrentScene();
        if (!scene) {
            console.error('❌ 无法获取当前场景');
            return;
        }
        if (!scene.transformControlsManager) {
            console.error('❌ Transform 控制器管理器未初始化');
        }
    };
    
    // 聚焦模式状态跟踪
    let lastFocusState = {
        nodeId: null,        // 上次聚焦的节点ID
        mode: 'withChildren' // 当前聚焦模式：'self' 或 'withChildren'，初始为withChildren，这样第一次按F会切换到self
    };
    
    // 键盘快捷键：Transform 模式切换 + 聚焦 + 批量删除
    window.addEventListener('keydown', (event) => {
        // 如果在输入框中，不触发快捷键
        if (event.target.tagName === 'INPUT' || event.target.tagName === 'TEXTAREA') {
            return;
        }
        
        // Delete - 批量删除选中节点
        if (event.key === 'Delete' && sceneTreeUI && sceneTreeUI.selectedNodes.length > 0) {
            event.preventDefault();
            sceneTreeUI.deleteSelectedNodes();
        }
        // W - 平移模式
        else if (event.key === 'w' || event.key === 'W') {
            event.preventDefault();
            window.setTransformMode('translate');
        }
        // E - 旋转模式
        else if (event.key === 'e' || event.key === 'E') {
            event.preventDefault();
            window.setTransformMode('rotate');
        }
        // R - 缩放模式
        else if (event.key === 'r' || event.key === 'R') {
            event.preventDefault();
            window.setTransformMode('scale');
        }
        // F - 聚焦到当前目标（支持模式切换）
        else if (event.key === 'f' || event.key === 'F') {
            event.preventDefault();
            
            // 使用统一的聚焦目标管理
            if (sceneTreeUI && sceneTreeUI._focusTarget) {
                const targetObject = sceneTreeUI._focusTarget;
                const targetType = sceneTreeUI._focusTargetType;
                
                // 获取当前场景的相机控制器
                const currentScene = manager.getCurrentScene();
                
                if (currentScene && currentScene.cameraController) {
                    // 生成目标的唯一ID（用于判断是否是同一个目标）
                    const targetId = targetObject.uuid;
                    const isSameTarget = lastFocusState.nodeId === targetId;
                    
                    let focusMode;
                    if (isSameTarget) {
                        // 同一个目标，切换模式：含子孙节点 <-> 自身
                        focusMode = lastFocusState.mode === 'withChildren' ? 'self' : 'withChildren';
                    } else {
                        // 新目标，第一次按F使用包围盒模式（含子孙节点）
                        focusMode = 'withChildren';
                    }
                    
                    // 更新状态
                    lastFocusState = {
                        nodeId: targetId,
                        mode: focusMode
                    };
                    
                    // 执行聚焦：selfOnly = true 表示只聚焦自身
                    const selfOnly = (focusMode === 'self');
                    currentScene.cameraController.focusOn(targetObject, 600, selfOnly);
                } else {
                    console.warn('⚠️ 未找到相机控制器');
                }
            }
        }
    });
    
    // 全局函数：切换比例尺显示
    window.toggleScaleGrid = function() {
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.toggleScaleGrid) {
            currentScene.toggleScaleGrid();
            
            // 更新按钮激活状态
            const btn = document.getElementById('scaleGridBtn');
            if (btn && currentScene.scaleGrid) {
                if (currentScene.scaleGrid.visible) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            }
        } else {
            console.warn('⚠️ 当前场景不支持比例尺功能');
        }
    };
    
    // 全局函数：切换参考地面显示
    window.toggleGroundPlane = function() {
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.toggleGroundPlane) {
            currentScene.toggleGroundPlane();
            
            // 更新按钮激活状态
            const btn = document.getElementById('groundPlaneBtn');
            if (btn) {
                // 检查地面是否可见
                let isGroundVisible = false;
                if (currentScene.scene) {
                    currentScene.scene.traverse((object) => {
                        if (object.userData && object.userData.isGround && object.visible) {
                            isGroundVisible = true;
                        }
                    });
                }
                
                if (isGroundVisible) {
                    btn.classList.add('active');
                } else {
                    btn.classList.remove('active');
                }
            }
        } else {
            console.warn('⚠️ 当前场景不支持参考地面功能');
        }
    };
    
    // 全局函数：切换左侧面板Tab
    window.switchLeftPanelTab = function(tabName) {
        // 更新Tab按钮状态
        const tabBtns = document.querySelectorAll('#scene-panel .tab-btn');
        tabBtns.forEach(btn => {
            if (btn.dataset.tab === tabName) {
                btn.classList.add('active');
            } else {
                btn.classList.remove('active');
            }
        });
        
        // 更新Tab内容显示
        const sceneTreeTab = document.getElementById('scene-tree-tab');
        const environmentTab = document.getElementById('environment-tab');
        
        if (tabName === 'scene-tree') {
            sceneTreeTab.classList.add('active');
            environmentTab.classList.remove('active');
        } else if (tabName === 'environment') {
            sceneTreeTab.classList.remove('active');
            environmentTab.classList.add('active');
            updateEnvironmentUI(); // 切换到环境Tab时更新UI
        }
    };
    
    // 更新环境UI显示
    function updateEnvironmentUI() {
        const currentScene = manager.getCurrentScene();
        if (!currentScene) return;
        
        // 更新相机位置显示
        if (currentScene.camera) {
            document.getElementById('camera-pos-x').value = currentScene.camera.position.x.toFixed(1);
            document.getElementById('camera-pos-y').value = currentScene.camera.position.y.toFixed(1);
            document.getElementById('camera-pos-z').value = currentScene.camera.position.z.toFixed(1);
        }
        
        // 更新比例尺状态
        if (currentScene.scaleGrid) {
            document.getElementById('scale-grid-visible').checked = currentScene.scaleGrid.visible;
        }
    }
    
    // 全局函数：重置相机
    window.resetCamera = function() {
        const currentScene = manager.getCurrentScene();
        if (currentScene && currentScene.cameraController) {
            currentScene.cameraController.reset();
            updateEnvironmentUI();
        }
    };
    
    // 全局函数：更新环境光
    window.updateAmbientLight = function() {
        const currentScene = manager.getCurrentScene();
        if (!currentScene) return;
        
        const intensity = parseFloat(document.getElementById('ambient-light-intensity').value);
        const color = document.getElementById('ambient-light-color').value;
        
        // 查找环境光
        const ambientLight = currentScene.lights.find(light => light.isAmbientLight);
        if (ambientLight) {
            ambientLight.intensity = intensity;
            ambientLight.color.set(color);
            document.getElementById('ambient-light-value').textContent = intensity.toFixed(1);
        }
    };
    
    // 全局函数：更新方向光
    window.updateDirectionalLight = function() {
        const currentScene = manager.getCurrentScene();
        if (!currentScene) return;
        
        const intensity = parseFloat(document.getElementById('directional-light-intensity').value);
        const color = document.getElementById('directional-light-color').value;
        
        // 查找方向光
        const directionalLight = currentScene.lights.find(light => light.isDirectionalLight);
        if (directionalLight) {
            directionalLight.intensity = intensity;
            directionalLight.color.set(color);
            document.getElementById('directional-light-value').textContent = intensity.toFixed(1);
        }
    };
    
    // 全局函数：切换地面显示
    window.toggleGround = function() {
        const currentScene = manager.getCurrentScene();
        if (!currentScene) return;
        
        const visible = document.getElementById('ground-visible').checked;
        
        // 查找所有地面相关对象（地面和网格辅助线）
        currentScene.scene.children.forEach(obj => {
            if (obj.userData && obj.userData.isGround) {
                obj.visible = visible;
            }
        });
    };
    
    // 全局函数：更新网格大小
    window.updateGridSize = function() {
        const currentScene = manager.getCurrentScene();
        if (!currentScene) return;
        
        const gridSize = parseInt(document.getElementById('grid-size').value);
        
        if (currentScene.scaleGrid) {
            currentScene.scaleGrid.updateGridSize(gridSize);
        }
    };
    
    // 全局函数：展开所有节点
    window.expandAllNodes = function() {
        if (sceneTreeUI) {
            sceneTreeUI.expandAll();
        }
    };
    
    // 全局函数：折叠所有节点
    window.collapseAllNodes = function() {
        if (sceneTreeUI) {
            sceneTreeUI.collapseAll();
        }
    };
    
    // 全局函数：清除所有节点选择
    window.clearNodeSelection = function() {
        if (sceneTreeUI) {
            sceneTreeUI.clearAllSelection();
        }
    };
    
    // 全局函数：切换Mesh结构面板
    window.toggleMeshStructurePanel = function() {
        const meshPanel = document.getElementById('mesh-structure-panel');
        const toggleBtn = document.getElementById('toggleMeshStructureBtn');
        
        if (!meshPanel) {
            console.error('❌ mesh结构面板未找到');
            return;
        }
        
        const isActive = meshPanel.classList.contains('active');
        
        if (isActive) {
            // 关闭面板 - 复用统一的退出Mesh编辑模式接口
            if (sceneTreeUI && typeof sceneTreeUI.exitMeshEditMode === 'function') {
                sceneTreeUI.exitMeshEditMode();
            }
            if (toggleBtn) toggleBtn.classList.remove('active');
        } else {
            // 打开面板前，检查当前节点是否有模型
            if (sceneTreeUI && sceneTreeUI.treeManager.selectedNode) {
                if (!sceneTreeUI.nodeHasModel(sceneTreeUI.treeManager.selectedNode)) {
                    console.warn('⚠️ 当前节点没有mesh数据');
                    if (window.showMessage) {
                        window.showMessage('该节点没有mesh数据，无法显示Mesh结构', 'warning');
                    }
                    return;
                }
                
                // ⭐ 使用统一的显示mesh面板方法（内部处理补位逻辑）
                sceneTreeUI.showMeshPanel();
                if (toggleBtn) toggleBtn.classList.add('active');
                
                // 显示其mesh结构
                sceneTreeUI.updateMeshStructurePanel(sceneTreeUI.treeManager.selectedNode);
            } else {
                console.warn('⚠️ 请先选择一个节点');
                if (window.showMessage) {
                    window.showMessage('请先选择一个节点', 'warning');
                }
            }
        }
    };
    
    // 全局函数：关闭Mesh结构面板
    window.closeMeshStructurePanel = function() {
        const toggleBtn = document.getElementById('toggleMeshStructureBtn');
        
        // 复用统一的退出Mesh编辑模式接口
        if (sceneTreeUI && typeof sceneTreeUI.exitMeshEditMode === 'function') {
            sceneTreeUI.exitMeshEditMode();
        }
        
        if (toggleBtn) {
            toggleBtn.classList.remove('active');
        }
    };
    
    // 注：toggleScenePanel函数已删除，现在使用tab按钮独立控制面板显隐
    
    // 全局函数：切换Mesh节点的展开/折叠
    window.toggleMeshNode = function(toggleElement) {
        const nodeItem = toggleElement.closest('.mesh-tree-item');
        if (!nodeItem) return;
        
        const childrenContainer = nodeItem.querySelector('.mesh-node-children');
        if (!childrenContainer) return;
        
        const isExpanded = childrenContainer.classList.contains('expanded');
        
        if (isExpanded) {
            // 折叠
            childrenContainer.classList.remove('expanded');
            toggleElement.textContent = '▶';
            toggleElement.classList.remove('expanded');
        } else {
            // 展开
            childrenContainer.classList.add('expanded');
            toggleElement.textContent = '▼';
            toggleElement.classList.add('expanded');
        }
    };
    
    // 全局变量：记录当前展开的层级
    window.meshExpandLevel = 0;
    
    // 🔧 全局函数：诊断纹理质量
    window.diagnoseTextures = function() {
        console.clear();
        console.log('%c🔍 ===== 纹理质量诊断报告 =====', 'font-size: 16px; font-weight: bold; color: #4CAF50');
        console.log('');
        
        // 详细的环境检查
        if (!window.manager) {
            console.error('❌ manager 未初始化！');
            console.log('%c💡 请按以下步骤操作：', 'color: #2196F3; font-weight: bold');
            console.log('1. 确保编辑器已完全加载');
            console.log('2. 等待加载完成');
            console.log('3. 再次运行此命令');
            return;
        }
        
        const currentScene = window.manager.getCurrentScene();
        if (!currentScene || !currentScene.scene) {
            console.error('❌ 场景未加载！');
            console.log('%c💡 请按以下步骤操作：', 'color: #2196F3; font-weight: bold');
            console.log('1. 在左侧场景列表中选择一个场景');
            console.log('2. 等待场景加载完成（加载界面消失）');
            console.log('3. 再次运行 diagnoseTextures()');
            console.log('');
            console.log('%c或者运行：', 'color: #ff9800; font-weight: bold');
            console.log('autoFix()  // 自动等待场景加载并修复');
            return;
        }
        
        if (!window.manager.renderer) {
            console.error('❌ 渲染器未初始化！');
            return;
        }
        
        const scene = currentScene.scene;
        const renderer = window.manager.renderer;
        const maxAnisotropy = renderer.capabilities.getMaxAnisotropy();
        
        console.log(`📊 GPU 最大各向异性级别: ${maxAnisotropy}`);
        console.log('');
        
        const textures = new Map();
        let totalMeshes = 0;
        
        scene.traverse((obj) => {
            if (obj.isMesh) {
                totalMeshes++;
                const material = obj.material;
                if (!material) return;
                
                const materials = Array.isArray(material) ? material : [material];
                materials.forEach(mat => {
                    ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap'].forEach(prop => {
                        if (mat[prop] && mat[prop].isTexture && !textures.has(mat[prop].uuid)) {
                            textures.set(mat[prop].uuid, {
                                texture: mat[prop],
                                type: prop,
                                materialName: mat.name || '未命名',
                                meshName: obj.name || '未命名'
                            });
                        }
                    });
                });
            }
        });
        
        console.log(`📷 找到 ${textures.size} 个唯一纹理，应用在 ${totalMeshes} 个 mesh 上\n`);
        
        let issues = { noMipmaps: 0, lowAnisotropy: 0, wrongFilter: 0, nonPOT: 0 };
        
        textures.forEach((info, uuid) => {
            const { texture, type, materialName, meshName } = info;
            console.group(`📷 ${meshName} / ${materialName} / ${type}`);
            
            if (texture.image) {
                const isPOT = (texture.image.width & (texture.image.width - 1)) === 0 && 
                             (texture.image.height & (texture.image.height - 1)) === 0;
                console.log(`尺寸: ${texture.image.width}x${texture.image.height} ${isPOT ? '✅' : '⚠️'}`);
                if (!isPOT) issues.nonPOT++;
            }
            
            const minOK = texture.minFilter === THREE.LinearMipmapLinearFilter;
            const magOK = texture.magFilter === THREE.LinearFilter;
            console.log(`minFilter: ${minOK ? '✅' : '❌ ' + texture.minFilter}`);
            console.log(`magFilter: ${magOK ? '✅' : '❌ ' + texture.magFilter}`);
            if (!minOK || !magOK) issues.wrongFilter++;
            
            const anisoOK = texture.anisotropy >= maxAnisotropy;
            console.log(`anisotropy: ${texture.anisotropy}/${maxAnisotropy} ${anisoOK ? '✅' : '❌'}`);
            if (!anisoOK) issues.lowAnisotropy++;
            
            const mipmapOK = texture.generateMipmaps === true;
            console.log(`generateMipmaps: ${mipmapOK ? '✅' : '❌'}`);
            if (!mipmapOK) issues.noMipmaps++;
            
            console.groupEnd();
        });
        
        console.log('\n%c📊 ===== 问题汇总 =====', 'font-size: 14px; font-weight: bold');
        console.log(`未启用 Mipmap: ${issues.noMipmaps} ${issues.noMipmaps ? '❌' : '✅'}`);
        console.log(`各向异性过低: ${issues.lowAnisotropy} ${issues.lowAnisotropy ? '❌' : '✅'}`);
        console.log(`过滤器错误: ${issues.wrongFilter} ${issues.wrongFilter ? '❌' : '✅'}`);
        console.log(`非2的幂尺寸: ${issues.nonPOT} ${issues.nonPOT ? '⚠️' : '✅'}`);
        
        const hasIssues = issues.noMipmaps + issues.lowAnisotropy + issues.wrongFilter > 0;
        if (hasIssues) {
            console.log('\n%c⚠️ 发现问题！运行 fixTextures() 立即修复', 'font-size: 14px; color: #f44336; font-weight: bold');
        } else {
            console.log('\n%c✅ 所有纹理设置完美！', 'font-size: 14px; color: #4CAF50; font-weight: bold');
        }
    };
    
    // 🔧 全局函数：修复所有纹理
    window.fixTextures = function() {
        console.clear();
        console.log('%c🔧 ===== 修复纹理质量 =====', 'font-size: 16px; font-weight: bold; color: #4CAF50');
        
        if (!window.manager) {
            console.error('❌ manager 未初始化！请等待编辑器加载完成。');
            return;
        }
        
        const currentScene = window.manager.getCurrentScene();
        if (!currentScene || !currentScene.scene) {
            console.error('❌ 场景未加载！请先打开一个场景。');
            console.log('%c💡 提示：在左侧场景列表中点击一个场景打开', 'color: #2196F3');
            return;
        }
        
        if (!window.manager.renderer) {
            console.error('❌ 渲染器未初始化！');
            return;
        }
        
        const scene = currentScene.scene;
        const renderer = window.manager.renderer;
        const maxAnisotropy = renderer.capabilities.getMaxAnisotropy();
        
        let fixedCount = 0;
        const processed = new Set();
        
        scene.traverse((obj) => {
            if (obj.isMesh && obj.material) {
                const materials = Array.isArray(obj.material) ? obj.material : [obj.material];
                materials.forEach(mat => {
                    ['map', 'normalMap', 'bumpMap', 'aoMap', 'roughnessMap', 'metalnessMap', 'emissiveMap'].forEach(prop => {
                        const tex = mat[prop];
                        if (tex && tex.isTexture && !processed.has(tex.uuid)) {
                            processed.add(tex.uuid);
                            tex.generateMipmaps = true;
                            tex.minFilter = THREE.LinearMipmapLinearFilter;
                            tex.magFilter = THREE.LinearFilter;
                            tex.anisotropy = maxAnisotropy;
                            tex.needsUpdate = true;
                            fixedCount++;
                            console.log(`✅ 修复 #${fixedCount}: ${obj.name}/${mat.name}/${prop}`);
                        }
                    });
                    mat.needsUpdate = true;
                });
            }
        });
        
        if (window.manager.render) window.manager.render();
        
        console.log(`\n%c✅ 完成！共修复 ${fixedCount} 个纹理`, 'font-size: 14px; font-weight: bold; color: #4CAF50');
        console.log('%c💡 如效果仍不佳，请刷新页面重新加载场景', 'color: #2196F3');
    };
    
    // 🚀 全局函数：自动等待场景加载并修复
    window.autoFix = function() {
        console.clear();
        console.log('%c🚀 ===== 自动修复纹理 =====', 'font-size: 16px; font-weight: bold; color: #4CAF50');
        console.log('');
        
        // 检查是否已经加载场景
        if (window.manager && window.manager.getCurrentScene()?.scene) {
            console.log('✅ 检测到场景已加载，立即开始修复...\n');
            window.fixTextures();
            return;
        }
        
        console.log('⏳ 场景尚未加载，开始等待...');
        console.log('💡 提示：请在左侧场景列表中选择一个场景\n');
        
        let attempts = 0;
        const maxAttempts = 60; // 最多等待60秒
        
        const checkInterval = setInterval(() => {
            attempts++;
            
            if (window.manager && window.manager.getCurrentScene()?.scene) {
                clearInterval(checkInterval);
                console.log(`✅ 场景加载完成！(等待了 ${attempts} 秒)`);
                console.log('');
                window.fixTextures();
            } else if (attempts >= maxAttempts) {
                clearInterval(checkInterval);
                console.error('❌ 等待超时！场景仍未加载。');
                console.log('%c💡 请手动：', 'color: #2196F3; font-weight: bold');
                console.log('1. 在左侧场景列表中点击一个场景');
                console.log('2. 等待场景加载完成');
                console.log('3. 运行：fixTextures()');
            } else if (attempts % 5 === 0) {
                console.log(`⏳ 继续等待... (${attempts}/${maxAttempts} 秒)`);
            }
        }, 1000);
    };
    
    // 全局函数：逐层展开Mesh节点
    window.expandAllMeshNodes = function() {
        const meshPanel = document.getElementById('mesh-structure-panel');
        if (!meshPanel) return;
        
        // 增加展开层级
        window.meshExpandLevel++;
        
        // 获取mesh树容器的直接子节点（根节点）
        const meshTreeContainer = meshPanel.querySelector('#mesh-tree-container');
        if (!meshTreeContainer) return;
        
        // 递归函数：展开到指定层级
        function expandToLevel(element, currentLevel) {
            const items = element.querySelectorAll(':scope > .mesh-tree-item');
            
            items.forEach(item => {
                const childrenContainer = item.querySelector(':scope > .mesh-node-children');
                const toggle = item.querySelector(':scope > .mesh-node-toggle:not(.empty)');
                
                if (childrenContainer) {
                    if (currentLevel < window.meshExpandLevel) {
                        // 当前层级小于目标层级，展开
                        childrenContainer.classList.add('expanded');
                        if (toggle) {
                            toggle.classList.add('expanded');
                            toggle.textContent = '▼';
                        }
                        // 递归处理子节点
                        expandToLevel(childrenContainer, currentLevel + 1);
                    } else {
                        // 当前层级等于或大于目标层级，折叠
                        childrenContainer.classList.remove('expanded');
                        if (toggle) {
                            toggle.classList.remove('expanded');
                            toggle.textContent = '▶';
                        }
                    }
                }
            });
        }
        
        // 从第0层开始展开
        expandToLevel(meshTreeContainer, 0);
    };
    
    // 全局函数：折叠所有Mesh节点
    window.collapseAllMeshNodes = function() {
        const meshPanel = document.getElementById('mesh-structure-panel');
        if (!meshPanel) return;
        
        // 重置展开层级计数器
        window.meshExpandLevel = 0;
        
        // 折叠所有子节点容器
        const allChildren = meshPanel.querySelectorAll('.mesh-node-children');
        allChildren.forEach(container => {
            container.classList.remove('expanded');
        });
        
        // 更新所有toggle按钮
        const allToggles = meshPanel.querySelectorAll('.mesh-node-toggle:not(.empty)');
        allToggles.forEach(toggle => {
            toggle.classList.remove('expanded');
            toggle.textContent = '▶';
        });
    };
    
    // 全局函数：切换Mesh显隐
    window.toggleMeshVisibility = function(button) {
        const meshUuid = button.dataset.uuid;
        if (!meshUuid) {
            console.warn('⚠️ 按钮缺少 uuid 属性');
            return;
        }
        
        if (!sceneTreeUI) {
            console.warn('⚠️ 场景树UI未初始化');
            return;
        }
        
        // 🔧 修复：多种方式获取场景节点，确保不选中mesh时也能工作
        let sceneNode = null;
        
        // 方法1：优先使用选中的场景树节点
        if (sceneTreeUI.treeManager.selectedNode) {
            sceneNode = sceneTreeUI.treeManager.selectedNode;
        }
        // 方法2：使用mesh编辑模式的节点
        else if (sceneTreeUI._currentMeshEditNode) {
            sceneNode = sceneTreeUI._currentMeshEditNode;
            console.log('💡 使用 mesh 编辑模式节点:', sceneNode.name);
        }
        // 方法3：从按钮的data-node-id属性获取节点
        else if (button.dataset.nodeId) {
            const nodeId = button.dataset.nodeId;
            sceneNode = sceneTreeUI.treeManager.findNodeById(nodeId);
            if (sceneNode) {
                console.log('💡 从按钮属性获取节点:', sceneNode.name);
            }
        }
        // 方法4：从meshNodeCache缓存获取节点
        else if (sceneTreeUI.meshNodeCache && sceneTreeUI.meshNodeCache.has(meshUuid)) {
            sceneNode = sceneTreeUI.meshNodeCache.get(meshUuid);
            if (sceneNode) {
                console.log('💡 从缓存获取节点:', sceneNode.name);
            }
        }
        
        if (!sceneNode) {
            console.warn('⚠️ 没有可用的场景树节点', {
                meshUuid,
                hasSelectedNode: !!sceneTreeUI.treeManager.selectedNode,
                hasEditNode: !!sceneTreeUI._currentMeshEditNode,
                buttonNodeId: button.dataset.nodeId,
                hasMeshCache: !!(sceneTreeUI.meshNodeCache && sceneTreeUI.meshNodeCache.size > 0)
            });
            return;
        }
        
        // 检查节点是否有 object3D
        if (!sceneNode.object3D) {
            console.warn('⚠️ 场景节点没有 object3D 属性');
            return;
        }
        
        // 🔧 修复：递归查找对应的 mesh 对象
        let meshObject = null;
        
        // 方法1：使用 Three.js 的 getObjectByProperty（递归查找）
        meshObject = sceneNode.object3D.getObjectByProperty('uuid', meshUuid);
        
        // 方法2：如果方法1失败，手动递归查找
        if (!meshObject) {
            sceneNode.object3D.traverse((obj) => {
                if (obj.uuid === meshUuid && obj.isMesh) {
                    meshObject = obj;
                }
            });
        }
        
        // 验证找到的对象
        if (!meshObject) {
            console.warn('⚠️ 未找到对应的Mesh对象', {
                meshUuid,
                nodeId: sceneNode.id,
                nodeName: sceneNode.name,
                hasObject3D: !!sceneNode.object3D
            });
            return;
        }
        
        if (!meshObject.isMesh) {
            console.warn('⚠️ 找到的对象不是Mesh', {
                uuid: meshUuid,
                type: meshObject.type
            });
            return;
        }
        
        console.log('✅ 找到 Mesh 对象:', {
            name: meshObject.name,
            uuid: meshObject.uuid,
            currentVisible: meshObject.visible
        });
        
        // 切换可见性
        meshObject.visible = !meshObject.visible;
        
        // 更新按钮状态
        if (meshObject.visible) {
            button.classList.remove('hidden');
            button.textContent = '👁';
            button.title = '隐藏';
        } else {
            button.classList.add('hidden');
            button.textContent = '👁‍🗨';
            button.title = '显示';
        }
        
        // 触发渲染更新
        if (window.manager && window.manager.render) {
            window.manager.render();
        }
        
        console.log('✅ Mesh 可见性已切换:', meshObject.visible);
    };
    
    // 全局函数：切换网格线显示
    window.toggleMeshWireframe = function() {
        const toggleBtn = document.getElementById('toggleWireframeBtn');
        
        if (!sceneTreeUI || !sceneTreeUI.treeManager.selectedNode) {
            console.warn('⚠️ 没有选中的场景树节点');
            return;
        }
        
        const sceneNode = sceneTreeUI.treeManager.selectedNode;
        
        // 切换网格线状态
        if (sceneTreeUI._wireframeEnabled) {
            // 关闭网格线
            sceneTreeUI.disableWireframe(sceneNode);
            if (toggleBtn) {
                toggleBtn.classList.remove('active');
            }
        } else {
            // 开启网格线
            sceneTreeUI.enableWireframe(sceneNode);
            if (toggleBtn) {
                toggleBtn.classList.add('active');
            }
        }
    };
    
    // 全局函数：重置mesh变换
    window.resetMeshTransform = function() {
        if (!sceneTreeUI) {
            console.warn('⚠️ 场景树UI未初始化');
            return;
        }
        
        // 调用SceneTreeUI的重置方法
        sceneTreeUI.resetCurrentMeshTransform();
    };

    // 动态生成场景下拉列表 - 已移除UI，保留函数框架避免报错
    function createSceneSelector() {
        // 场景下拉框已移除，此函数保留为空以避免调用错误
    }
    
    // 获取场景类型对应的图标
    function getSceneIcon(sceneType) {
        const iconMap = {
            'GroundScene': '🏞️'
        };
        return iconMap[sceneType] || '🎬';
    }

    // 更新场景计数
    updateSceneInfo();
    function updateSceneInfo() {
        const currentScene = manager.getCurrentScene();
        const currentSceneName = manager.getCurrentSceneName();
        const sceneNames = manager.getSceneNames();
        
        // 更新场景名称显示
        const sceneNameElement = document.getElementById('current-scene-name');
        if (sceneNameElement && currentSceneName) {
            // 从场景配置中获取场景名称（带图标）
            const scenes = projectManager.getScenes();
            const sceneConfig = scenes.find(s => s.id === currentSceneName);
            if (sceneConfig) {
                const icon = getSceneIcon(sceneConfig.type);
                sceneNameElement.textContent = sceneConfig.name;
            } else {
                sceneNameElement.textContent = currentSceneName;
            }
        }
    }

    // ============ 项目管理面板 ============
    
    let apiAvailable = false;
    
    // 打开项目管理面板
    document.getElementById('projectBtn').addEventListener('click', async function() {
        const panel = document.getElementById('project-panel');
        const overlay = document.getElementById('project-panel-overlay');
        panel.style.display = 'flex';
        overlay.style.display = 'block';
        
        // 检查API服务
        apiAvailable = await projectAPI.checkConnection();
        if (!apiAvailable) {
            console.warn('⚠️ API服务未启动，使用本地模式');
        }
        
        await loadProjectPanel();
    });
    
    // 关闭项目管理面板
    function closeProjectPanel() {
        document.getElementById('project-panel').style.display = 'none';
        document.getElementById('project-panel-overlay').style.display = 'none';
    }
    
    document.getElementById('closeProjectPanel').addEventListener('click', closeProjectPanel);
    
    // 点击遮罩层关闭面板
    document.getElementById('project-panel-overlay').addEventListener('click', closeProjectPanel);
    
    // 加载项目管理面板内容
    async function loadProjectPanel() {
        // 先刷新项目列表，确保显示最新数据
        try {
            await projectManager.refreshProjects();
        } catch (error) {
            console.warn('⚠️ 刷新项目列表失败，使用缓存数据:', error);
        }
        
        // 显示当前项目
        updateCurrentProjectDisplay();
        
        // 显示所有项目列表
        updateProjectList();
    }
    
    // 更新当前项目显示
    function updateCurrentProjectDisplay() {
        const current = projectManager.getCurrentProject();
        const display = document.getElementById('currentProjectDisplay');
        
        if (current) {
            const sceneCount = current.scenes ? current.scenes.length : 0;
            display.innerHTML = `
                <div class="project-name">✅ ${current.name}</div>
                <div class="project-meta">
                    <span>📊 场景数: ${sceneCount}</span>
                    <span>🕒 ${formatDate(current.updatedAt)}</span>
                </div>
            `;
            
            // 同时更新工具栏中的项目名称
            const projectNameElement = document.getElementById('current-project-name');
            if (projectNameElement) {
                projectNameElement.textContent = current.name;
            }
            
            // 更新浏览器标签页标题
            document.title = `${current.name} - 组态可视化系统`;
        } else {
            display.innerHTML = `
                <div class="project-name">未选择项目</div>
            `;
            
            // 重置浏览器标签页标题
            document.title = '组态可视化系统';
        }
    }
    
    // 更新项目列表
    async function updateProjectList() {
        const listContainer = document.getElementById('projectList');
        listContainer.innerHTML = '<div class="loading">加载中...</div>';
        
        try {
            let projects;
            let defaultProjectId;
            
            if (apiAvailable) {
                const data = await projectAPI.getAllProjects();
                projects = data.projects;
                defaultProjectId = data.defaultProject;
            } else {
                projects = projectManager.getAllProjects();
                defaultProjectId = projectManager.defaultProjectId;
            }
            
            const currentId = projectManager.getCurrentProject()?.id;
            
            if (projects.length === 0) {
                listContainer.innerHTML = `
                    <div class="loading">
                        暂无项目<br>
                        点击上方 "➕ 新建项目" 创建第一个项目
                    </div>
                `;
                return;
            }
            
            listContainer.innerHTML = projects.map(project => {
                const isCurrent = project.id === currentId;
                const isDefault = project.id === defaultProjectId;
                const sceneCount = project.scenes ? project.scenes.length : 0;
                
                return `
                    <div class="project-card ${isCurrent ? 'current' : ''}" data-project-id="${project.id}">
                        <div class="project-name">
                            ${isCurrent ? '✅ ' : ''}${project.name}
                            ${isDefault ? '<span class="default-badge">默认</span>' : ''}
                        </div>
                        <div class="project-meta">
                            <span>📊 ${sceneCount} 个场景</span>
                            <span>🕒 ${formatDate(project.updatedAt || project.createdAt)}</span>
                        </div>
                            <div class="project-actions">
                        ${!isCurrent ? `
                                <button class="btn-switch" onclick="switchToProject('${project.id}')">
                                    切换
                                </button>
                            ` : ''}
                            ${!isDefault ? `
                                <button class="btn-default" onclick="setAsDefaultProject('${project.id}', '${project.name.replace(/'/g, "\\'")}')">
                                    设为默认
                                </button>
                            ` : ''}
                            <button class="btn-edit" onclick="renameProjectById('${project.id}', '${project.name.replace(/'/g, "\\'")}')">
                                    重命名
                                </button>
                            ${!isCurrent ? `
                                <button class="btn-delete" onclick="deleteProjectById('${project.id}', '${project.name.replace(/'/g, "\\'")}')">
                                    删除
                                </button>
                        ` : ''}
                            </div>
                    </div>
                `;
            }).join('');
        } catch (error) {
            console.error('❌ 加载项目列表失败:', error);
            listContainer.innerHTML = `
                <div class="loading" style="color: #ff6b6b;">
                    加载失败<br>
                    ${apiAvailable ? '请检查API服务' : '请启动API服务器'}
                </div>
            `;
        }
    }
    
    // 格式化日期
    function formatDate(dateStr) {
        if (!dateStr) return '未知';
        const date = new Date(dateStr);
        const now = new Date();
        const diff = now - date;
        const days = Math.floor(diff / (1000 * 60 * 60 * 24));
        
        if (days === 0) return '今天';
        if (days === 1) return '昨天';
        if (days < 7) return `${days} 天前`;
        if (days < 30) return `${Math.floor(days / 7)} 周前`;
        
        return date.toLocaleDateString('zh-CN');
    }
    
    // 创建项目Modal
    window.openCreateProjectModal = function() {
        document.getElementById('createProjectModal').classList.add('active');
        document.getElementById('newProjectName').value = '';
    };
    
    window.closeCreateProjectModal = function() {
        document.getElementById('createProjectModal').classList.remove('active');
    };
    
    window.confirmCreateProject = async function() {
        // 防止重复点击
        if (window.isCreatingProject) {
            console.warn('⚠️ 项目正在创建中，请勿重复点击');
            return;
        }

        const name = document.getElementById('newProjectName').value.trim();
        
        if (!name) {
            alert('请输入项目名称');
            return;
        }

        // 设置创建中标志并禁用按钮
        window.isCreatingProject = true;
        const modal = document.getElementById('createProjectModal');
        const createBtn = modal.querySelector('button[onclick="confirmCreateProject()"]');
        const originalBtnText = createBtn.textContent;
        createBtn.disabled = true;
        createBtn.textContent = '创建中...';
        createBtn.style.opacity = '0.6';
        createBtn.style.cursor = 'not-allowed';
        
        try {
            if (apiAvailable) {
                await projectAPI.createProject(name, '');
                closeCreateProjectModal();
                alert('项目创建成功！');
                updateProjectList();
            } else {
                alert('创建项目需要启动 API 服务器');
            }
        } catch (error) {
            console.error('❌ 创建失败:', error);
            alert('创建失败: ' + error.message);
        } finally {
            // 恢复按钮状态
            window.isCreatingProject = false;
            createBtn.disabled = false;
            createBtn.textContent = originalBtnText;
            createBtn.style.opacity = '1';
            createBtn.style.cursor = 'pointer';
        }
    };
    
    // 创建新项目按钮
    document.getElementById('createProjectBtn').addEventListener('click', function() {
        openCreateProjectModal();
    });
    
    // ============ 场景管理功能 ============
    
    // 打开场景管理面板
    document.getElementById('sceneManageBtn').addEventListener('click', async function() {
        const panel = document.getElementById('scene-manage-panel');
        panel.classList.add('active');
        
        // 检查API服务
        apiAvailable = await projectAPI.checkConnection();
        if (!apiAvailable) {
            console.warn('⚠️ API服务未启动，使用本地模式');
        }
        
        await loadSceneManagePanel();
    });
    
    // 关闭场景管理面板
    document.getElementById('closeSceneManagePanel').addEventListener('click', function() {
        document.getElementById('scene-manage-panel').classList.remove('active');
    });
    
    // 点击遮罩关闭场景管理面板
    document.getElementById('scene-manage-panel').addEventListener('click', function(e) {
        if (e.target === this) {
            document.getElementById('scene-manage-panel').classList.remove('active');
        }
    });
    
    // 加载场景管理面板内容
    async function loadSceneManagePanel() {
        const listContainer = document.getElementById('sceneList');
        listContainer.innerHTML = '<div class="loading">加载中...</div>';
        
        try {
            // 刷新项目数据
            await projectManager.refreshProjects();
            await projectManager.loadProjectById(projectManager.getCurrentProject()?.id);
            window.currentProjectId = projectManager.getCurrentProject()?.id;
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                listContainer.innerHTML = '<div class="loading">未找到当前项目</div>';
                return;
            }
            
            const scenes = projectManager.getScenes();
            const currentSceneName = manager.getCurrentSceneName();
            const defaultSceneId = currentProject.defaultScene;
            
            if (scenes.length === 0) {
                listContainer.innerHTML = `
                    <div class="loading">
                        暂无场景<br>
                        点击上方 "➕ 新建场景" 创建第一个场景
                    </div>
                `;
                return;
            }
            
            listContainer.innerHTML = scenes.map(scene => {
                const isCurrent = scene.id === currentSceneName;
                const isDefault = scene.id === defaultSceneId;
                
                return `
                    <div class="scene-card ${isCurrent ? 'current' : ''}" data-scene-id="${scene.id}">
                        <div class="scene-header">
                            <div class="scene-icon">${scene.icon || '🏞️'}</div>
                            <div class="scene-info">
                                <div class="scene-name">
                                    ${isCurrent ? '▶️ ' : ''}${scene.name}
                                    ${isDefault ? '<span class="default-badge">默认</span>' : ''}
                                </div>
                                ${scene.description ? `<div class="scene-desc">${scene.description}</div>` : ''}
                            </div>
                        </div>
                        <div class="scene-actions">
                            ${!isCurrent ? `
                                <button class="btn-scene-switch" onclick="switchToScene('${scene.id}')">
                                    切换
                                </button>
                            ` : ''}
                            ${!isDefault ? `
                                <button class="btn-scene-default" onclick="setSceneAsDefault('${scene.id}', '${scene.name.replace(/'/g, "\\'")}')">
                                    设为默认
                                </button>
                            ` : ''}
                            <button class="btn-scene-edit" onclick="renameScene('${scene.id}', '${scene.name.replace(/'/g, "\\'")}')">
                                重命名
                            </button>
                            <button class="btn-scene-delete" onclick="deleteScene('${scene.id}', '${scene.name.replace(/'/g, "\\'")}')">
                                删除
                            </button>
                        </div>
                    </div>
                `;
            }).join('');
            
        } catch (error) {
            console.error('❌ 加载场景列表失败:', error);
            listContainer.innerHTML = `
                <div class="loading" style="color: #ff6b6b;">
                    加载失败<br>
                    ${error.message}
                </div>
            `;
        }
    }
    
    // 创建场景按钮
    document.getElementById('createSceneBtn').addEventListener('click', function() {
        openCreateSceneModal();
    });
    
    // 创建场景Modal函数
    window.openCreateSceneModal = function() {
        document.getElementById('createSceneModal').classList.add('active');
        document.getElementById('newSceneName').value = '';
        document.getElementById('newSceneDescription').value = '';
    };
    
    window.closeCreateSceneModal = function() {
        document.getElementById('createSceneModal').classList.remove('active');
    };
    
    window.confirmCreateScene = async function() {
        const name = document.getElementById('newSceneName').value.trim();
        const description = document.getElementById('newSceneDescription').value.trim();
        
        if (!name) {
            alert('请输入场景名称');
            return;
        }
        
        try {
            if (!apiAvailable) {
                alert('创建场景需要启动 API 服务器');
                return;
            }
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                alert('未找到当前项目');
                return;
            }
            // 通过API创建场景（默认GroundScene类型）
            const newScene = await projectAPI.addScene(currentProject.id, {
                name,
                description
            });
            // 刷新项目数据
            await projectManager.refreshProjects();
            await projectManager.loadProjectById(currentProject.id);
            window.currentProjectId = currentProject.id;
            
            // 注册新场景到场景管理器（默认使用GroundScene）
            manager.registerScene(newScene.id, GroundScene);
            // 刷新UI
            createSceneSelector();
            await loadSceneManagePanel();
            
            // 关闭Modal
            closeCreateSceneModal();
            
            alert(`场景 "${name}" 创建成功！`);
            
        } catch (error) {
            console.error('❌ 创建场景失败:', error);
            alert('创建场景失败: ' + error.message);
        }
    };
    
    // 切换到场景
    window.switchToScene = async function(sceneId) {
        // ⭐ 步骤1: 强制关闭所有面板（包括材质编辑器、模型库、Transform等）
        if (window.rightToolbarManager) {
            const allClosed = await window.rightToolbarManager.closeAllPanels();
            if (!allClosed) {
                return; // 用户取消或保存失败，不进行场景切换
            }
        }
        
        // ⭐ 步骤2: 强制移除所有面板的show类（双重保障）
        const allPanels = document.querySelectorAll('.right-panel.show');
        allPanels.forEach(panel => {
            panel.classList.remove('show');
        });
        
        // 清空currentActivePanel状态
        if (window.rightToolbarManager) {
            window.rightToolbarManager.currentActivePanel = null;
        }
        // ⭐ 步骤3: 退出Mesh编辑模式（关闭Mesh结构面板）
        if (window.sceneTreeUI && typeof window.sceneTreeUI.exitMeshEditMode === 'function') {
            window.sceneTreeUI.exitMeshEditMode();
        }
        
        // ⭐ 步骤3.5: 关闭材质编辑器内的所有弹窗（预览窗口、引用信息面板）
        if (window.rightToolbarManager && window.rightToolbarManager.materialEditorPanel) {
            window.rightToolbarManager.materialEditorPanel.closeAllPopups();
        }
        
        // ⭐ 步骤4: 取消当前场景树的节点选择
        if (window.sceneTreeManager) {
            window.sceneTreeManager.deselectNode();
        }
        
        // ⭐ 步骤5: 关闭场景管理界面
        const sceneManagePanel = document.getElementById('scene-manage-panel');
        if (sceneManagePanel) {
            sceneManagePanel.classList.remove('active');
        }
        
        // ⭐ 步骤6: 执行场景切换
        await sceneLoader.performSceneLoading(async (loader) => {
            loader.updateStage('single-scene', 0, '正在切换场景...');
            
            // 销毁旧的环境管理器
            if (window.environmentManager) {
                window.environmentManager.dispose();
                window.environmentManager = null;
            }
            
            const success = manager.switchScene(sceneId);
            
            if (!success) {
                throw new Error('场景切换失败');
            }
            
            loader.updateStage('single-scene', 10, '更新场景信息...');
            updateSceneInfo();
            loadSceneManagePanel(); // 刷新场景列表
            
            const currentScene = manager.getCurrentScene();
            if (currentScene && currentScene.scene) {
                // ===== 步骤1: 优先加载环境模型 (10-25%) =====
                loader.updateStage('single-scene', 15, '正在初始化环境...');
                
                // 创建环境管理器
                const environmentManager = new EnvironmentManager(
                    currentScene.scene,
                    currentProject.id,
                    sceneId
                );
                
                // 初始化环境管理器（加载配置）
                await environmentManager.initialize();
                
                // 加载环境模型（如果有配置）
                if (environmentManager.config.environmentModel) {
                    await environmentManager.loadEnvironmentModel((progress, detail) => {
                        const p = 15 + Math.round((progress / 100) * 10); // 15-25%
                        loader.updateStage('single-scene', p, detail);
                    });
                }
                
                // 暴露到全局
                window.environmentManager = environmentManager;
                
                // ===== 步骤2: 初始化场景树并加载场景树数据 (25-75%) =====
                loader.updateStage('single-scene', 25, '初始化场景树...');
                initializeSceneTree(currentScene.scene);
                
                // 加载新场景的树数据（使用 single-scene 阶段）
                await loadSceneTreeData(sceneId, loader, 25, 50, 'single-scene');
                
                // ===== 步骤3: 最后应用环境光配置 (75-85%) =====
                loader.updateStage('single-scene', 78, '正在应用环境光...');
                await environmentManager.applyAmbientLight();
                
                // 更新环境UI
                if (window.updateEnvironmentUI) {
                    window.updateEnvironmentUI();
                }
            }
            
            // ⭐ 步骤7: 场景加载完成后，再次确认所有面板已关闭
            loader.updateStage('single-scene', 90, '清理UI状态...');
            
            // 检查右侧面板
            const remainingPanels = document.querySelectorAll('.right-panel.show');
            if (remainingPanels.length > 0) {
                remainingPanels.forEach(panel => {
                    panel.classList.remove('show');
                });
            }
            
            // 检查Mesh结构面板
            const meshPanel = document.getElementById('mesh-structure-panel');
            if (meshPanel && meshPanel.classList.contains('active')) {
                if (window.sceneTreeUI && typeof window.sceneTreeUI.exitMeshEditMode === 'function') {
                    window.sceneTreeUI.exitMeshEditMode();
                }
            }
        });
    };
    
    // 设置为默认场景
    window.setSceneAsDefault = async function(sceneId, sceneName) {
        if (!confirm(`确定将 "${sceneName}" 设为默认场景吗？`)) {
            return;
        }
        
        try {
            if (!apiAvailable) {
                alert('设置默认场景需要启动 API 服务器');
                return;
            }
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                alert('未找到当前项目');
                return;
            }
            
            await projectAPI.setDefaultScene(currentProject.id, sceneId);
            
            // 刷新项目数据
            await projectManager.refreshProjects();
            await projectManager.loadProjectById(currentProject.id);
            window.currentProjectId = currentProject.id;
            alert(`已将 "${sceneName}" 设为默认场景`);
            
            await loadSceneManagePanel();
            
        } catch (error) {
            console.error('❌ 设置默认场景失败:', error);
            alert('设置失败: ' + error.message);
        }
    };
    
    // 重命名场景
    window.renameScene = async function(sceneId, currentName) {
        const newName = await showInputDialog({
            title: '重命名场景',
            message: '请输入新的场景名称：',
            defaultValue: currentName
        });
        if (!newName || newName === currentName) return;
        
        try {
            if (!apiAvailable) {
                alert('重命名场景需要启动 API 服务器');
                return;
            }
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                alert('未找到当前项目');
                return;
            }
            
            await projectAPI.updateScene(currentProject.id, sceneId, { name: newName });
            
            // 刷新项目数据
            await projectManager.refreshProjects();
            await projectManager.loadProjectById(currentProject.id);
            window.currentProjectId = currentProject.id;
            alert(`场景已重命名为 "${newName}"`);
            
            // 刷新UI
            createSceneSelector();
            await loadSceneManagePanel();
            
            // 如果重命名的是当前场景，更新顶部控制栏的场景名称
            const currentSceneName = manager.getCurrentSceneName();
            if (currentSceneName === sceneId) {
                updateSceneInfo();
            }
            
        } catch (error) {
            console.error('❌ 重命名失败:', error);
            alert('重命名失败: ' + error.message);
        }
    };
    
    // 删除场景
    window.deleteScene = async function(sceneId, sceneName) {
        if (!confirm(`确定要删除场景 "${sceneName}" 吗？\n\n⚠️ 此操作不可恢复！`)) {
            return;
        }
        
        try {
            if (!apiAvailable) {
                alert('删除场景需要启动 API 服务器');
                return;
            }
            
            const currentProject = projectManager.getCurrentProject();
            if (!currentProject) {
                alert('未找到当前项目');
                return;
            }
            
            // 检查是否是当前场景
            const currentSceneName = manager.getCurrentSceneName();
            if (sceneId === currentSceneName) {
                alert('不能删除当前正在使用的场景，请先切换到其他场景');
                return;
            }
            
            await projectAPI.deleteScene(currentProject.id, sceneId);
            
            // 刷新项目数据
            await projectManager.refreshProjects();
            await projectManager.loadProjectById(currentProject.id);
            window.currentProjectId = currentProject.id;
            alert('场景删除成功！');
            
            // 刷新UI
            createSceneSelector();
            await loadSceneManagePanel();
            
        } catch (error) {
            console.error('❌ 删除失败:', error);
            alert('删除失败: ' + error.message);
        }
    };
    
    // 点击Modal背景关闭
    document.getElementById('createSceneModal').addEventListener('click', function(e) {
        if (e.target === this) {
            closeCreateSceneModal();
        }
    });
    
    // 切换项目（简化版：直接刷新页面）
    window.switchToProject = async function(projectId) {
        try {
            // 🧹 卸载当前项目的材质库
            if (window.unloadMaterialLibraryManager) {
                window.unloadMaterialLibraryManager();
            }
            
            // 🧹 清理模型库资源（取消所有下载任务）
            if (window.cleanupModelLibrary) {
                window.cleanupModelLibrary();
            }
            
            // 直接刷新页面，不显示加载界面
            // 页面重新加载时会自动显示项目加载界面
            const currentUrl = new URL(window.location);
            currentUrl.searchParams.set('project', projectId);
            window.location.href = currentUrl.toString();
        } catch (error) {
            console.error('❌ 切换项目失败:', error);
            console.error('错误信息:', error.message);
            alert('切换项目失败: ' + error.message);
        }
    };
    
    // 重命名项目
    window.renameProjectById = async function(projectId, currentName) {
        const newName = await showInputDialog({
            title: '重命名项目',
            message: '请输入新的项目名称：',
            defaultValue: currentName
        });
        if (!newName || newName === currentName) return;
        
        try {
            if (apiAvailable) {
                await projectAPI.updateProject(projectId, { name: newName });
                // 重新从 API 获取最新的项目数据
                await projectManager.refreshProjects();
                
                // 如果重命名的是当前项目，需要重新加载当前项目
                const currentProjectId = projectManager.getCurrentProject()?.id;
                if (projectId === currentProjectId) {
                    await projectManager.loadProjectById(projectId);
                    window.currentProjectId = projectId;
                }
                
                alert(`项目已重命名为 "${newName}"`);
                updateProjectList();
                updateCurrentProjectDisplay();
            } else {
                alert('重命名功能需要启动 API 服务器');
            }
        } catch (error) {
            console.error('❌ 重命名失败:', error);
            alert('重命名失败: ' + error.message);
        }
    };
    
    // 删除项目
    window.deleteProjectById = async function(projectId, projectName) {
        if (!confirm(`确定要删除项目 "${projectName}" 吗？\n\n⚠️ 警告：此操作将永久删除项目文件夹和所有数据！`)) {
            return;
        }
        
        try {
            if (apiAvailable) {
                await projectAPI.deleteProject(projectId);
                alert('项目删除成功！');
                updateProjectList();
            } else {
                alert('删除功能需要启动 API 服务器');
            }
        } catch (error) {
            console.error('❌ 删除失败:', error);
            alert('删除失败: ' + error.message);
        }
    };
    
    // 设置默认项目
    window.setAsDefaultProject = async function(projectId, projectName) {
        try {
            if (apiAvailable) {
                await projectAPI.setDefaultProject(projectId);
                // 重新从 API 获取最新的项目数据（包括 defaultProject 信息）
                await projectManager.refreshProjects();
                
                alert(`已将 "${projectName}" 设置为默认项目！`);
                updateProjectList();
            } else {
                alert('设置默认项目需要启动 API 服务器');
            }
        } catch (error) {
            console.error('❌ 设置默认项目失败:', error);
            alert('设置失败: ' + error.message);
        }
    };
    
    // 项目模式切换功能 - 已移除（编辑端固定为编辑模式）

} catch (error) {
    console.error('\n╔════════════════════════════════════════════════════════╗');
    console.error('║           ❌ 应用初始化失败！                          ║');
    console.error('╚════════════════════════════════════════════════════════╝');
    console.error('错误详情:', error);
    document.body.innerHTML = `
        <div style="color: white; padding: 20px; font-family: monospace;">
            <h2>❌ 加载失败</h2>
            <p>错误信息: ${error.message}</p>
            <p>请打开浏览器控制台查看详细信息</p>
        </div>
    `;
}

// ============ 自定义确认对话框 ============

// 自定义确认对话框（替代浏览器confirm）
window.customConfirm = function(message, title = '确认操作') {
    return new Promise((resolve) => {
        const dialog = document.getElementById('custom-confirm-dialog');
        const titleEl = document.getElementById('confirm-dialog-title');
        const messageEl = document.getElementById('confirm-dialog-message');
        const confirmBtn = document.getElementById('confirm-dialog-confirm');
        const cancelBtn = document.getElementById('confirm-dialog-cancel');
        
        // 设置内容
        titleEl.textContent = title;
        messageEl.textContent = message;
        
        // 显示对话框
        dialog.classList.add('active');
        
        // 确定按钮处理
        const handleConfirm = () => {
            dialog.classList.remove('active');
            cleanup();
            resolve(true);
        };
        
        // 取消按钮处理
        const handleCancel = () => {
            dialog.classList.remove('active');
            cleanup();
            resolve(false);
        };
        
        // 清理事件监听
        const cleanup = () => {
            confirmBtn.removeEventListener('click', handleConfirm);
            cancelBtn.removeEventListener('click', handleCancel);
            dialog.removeEventListener('click', handleBackdropClick);
        };
        
        // 点击背景关闭
        const handleBackdropClick = (e) => {
            if (e.target === dialog) {
                handleCancel();
            }
        };
        
        // 绑定事件
        confirmBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        dialog.addEventListener('click', handleBackdropClick);
    });
};

// 自定义编辑模型信息对话框（全局单例模式，避免事件监听器堆叠）
window.showEditModelDialog = (function() {
    let currentCleanup = null; // 保存当前的清理函数
    
    return function(currentName, currentDescription, currentScale, currentTags) {
        // 如果有之前未清理的监听器，先清理
        if (currentCleanup) {
            currentCleanup();
            currentCleanup = null;
        }
        
        return new Promise((resolve) => {
            const dialog = document.getElementById('edit-model-dialog');
            const nameInput = document.getElementById('edit-model-name');
            const scaleInput = document.getElementById('edit-model-scale');
            const descInput = document.getElementById('edit-model-description');
            const tagsListContainer = document.getElementById('edit-model-tags-list');
            const tagsInput = document.getElementById('edit-model-tags-input');
            const addTagBtn = document.getElementById('add-tag-btn');
            const confirmBtn = document.getElementById('edit-model-confirm');
            const cancelBtn = document.getElementById('edit-model-cancel');
            
            // 存储当前标签
            let tags = currentTags ? [...currentTags] : [];
            // 渲染标签列表
            const renderTags = () => {
                if (tags.length === 0) {
                    tagsListContainer.innerHTML = '<div class="tags-empty-hint">暂无标签</div>';
                    return;
                }
                
                tagsListContainer.innerHTML = tags.map((tag, index) => `
                    <div class="tag-item">
                        <span class="tag-text">${tag}</span>
                        <button type="button" class="tag-remove-btn" data-index="${index}" title="删除标签">×</button>
                    </div>
                `).join('');
                
                // 绑定删除按钮事件
                tagsListContainer.querySelectorAll('.tag-remove-btn').forEach(btn => {
                    btn.addEventListener('click', () => {
                        const index = parseInt(btn.dataset.index);
                        const removedTag = tags[index];
                        // 直接删除，不需要确认
                        tags.splice(index, 1);
                        renderTags();
                    });
                });
            };
            
            // 添加标签
            const addTag = () => {
                const newTag = tagsInput.value.trim();
                if (!newTag) {
                    return;
                }
                
                // 检查是否已存在
                if (tags.includes(newTag)) {
                    alert('该标签已存在');
                    tagsInput.value = '';
                    tagsInput.focus();
                    return;
                }
                
                // 添加标签
                tags.push(newTag);
                tagsInput.value = '';
                renderTags();
                tagsInput.focus();
            };
            
            // 设置当前值
            nameInput.value = currentName || '';
            scaleInput.value = currentScale || 0.01;
            descInput.value = currentDescription || '';
            renderTags();
            
            // 显示对话框
            dialog.classList.add('active');
            
            // 聚焦到名称输入框
            setTimeout(() => {
                nameInput.focus();
                nameInput.select();
            }, 100);
            
            // 标签输入框回车键添加标签
            const handleTagsKeyPress = (e) => {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addTag();
                }
            };
            
            // 确定按钮处理
            const handleConfirm = () => {
                const newName = nameInput.value.trim();
                const newScale = parseFloat(scaleInput.value);
                const newDescription = descInput.value.trim();
                if (!newName) {
                    nameInput.focus();
                    return;
                }
                
                if (isNaN(newScale) || newScale <= 0) {
                    alert('缩放比例必须是大于0的数字');
                    scaleInput.focus();
                    return;
                }
                
                dialog.classList.remove('active');
                cleanup();
                resolve({ name: newName, scale: newScale, description: newDescription, tags: tags });
            };
            
            // 取消按钮处理
            const handleCancel = () => {
                dialog.classList.remove('active');
                cleanup();
                resolve(null);
            };
            
            // 禁用点击背景关闭（避免误操作导致数据丢失）
            const handleBackdropClick = (e) => {
                // 不做任何操作，必须通过取消或确定按钮关闭
            };
            
            // 回车键提交（仅在名称输入框）
            const handleKeyPress = (e) => {
                if (e.key === 'Enter' && e.target === nameInput) {
                    e.preventDefault();
                    handleConfirm();
                }
                // 禁用 Escape 键关闭，避免误触导致数据丢失
                // 用户必须明确点击取消或确定按钮
            };
            
            // 清理事件监听器
            const cleanup = () => {
                confirmBtn.removeEventListener('click', handleConfirm);
                cancelBtn.removeEventListener('click', handleCancel);
                nameInput.removeEventListener('keydown', handleKeyPress);
                addTagBtn.removeEventListener('click', addTag);
                tagsInput.removeEventListener('keydown', handleTagsKeyPress);
                currentCleanup = null; // 清理完成后重置
            };
            
            // 保存清理函数到全局
            currentCleanup = cleanup;
            
            // 添加事件监听器
            confirmBtn.addEventListener('click', handleConfirm);
            cancelBtn.addEventListener('click', handleCancel);
            nameInput.addEventListener('keydown', handleKeyPress);
            addTagBtn.addEventListener('click', addTag);
            tagsInput.addEventListener('keydown', handleTagsKeyPress);
        });
    };
})();

// 自定义提示消息（固定在屏幕顶部显示）
window.showManageMessage = function(message, type = 'success') {
    // 创建临时提示元素
    const messageEl = document.createElement('div');
    messageEl.className = `manage-message ${type}`;
    messageEl.innerHTML = `
        <span class="manage-message-icon">${type === 'success' ? '✅' : '❌'}</span>
        <span class="manage-message-text">${message}</span>
    `;
    
    // 添加到body，使用fixed定位不影响布局
    document.body.appendChild(messageEl);
    
    // 3秒后自动消失
    setTimeout(() => {
        messageEl.style.opacity = '0';
        setTimeout(() => messageEl.remove(), 300);
    }, 3000);
};

// === 页面卸载时清理资源 ===
window.addEventListener('beforeunload', () => {
    // 卸载材质库
    if (window.unloadMaterialLibraryManager) {
        window.unloadMaterialLibraryManager();
    }
    
    // 清理模型库资源（取消所有下载任务）
    if (window.cleanupModelLibrary) {
        window.cleanupModelLibrary();
    }
});
